<script lang="ts" setup>
import { Message, Modal } from '@arco-design/web-vue'
import { Workbook } from 'exceljs'
import { useDebounceFn } from '@vueuse/core'
import ClassStatus from './components/ClassStatus.vue'
import { ClassInfoApi } from '@/apis'
import type { TableInstanceColumns } from '@/components/ProTable/type'
import { useTable } from '@/hooks/modules/useTable'
import { useDictFilterOptions, useDownload, useForm } from '@/hooks'

defineOptions({
  name: 'ClassIndex',
})

const router = useRouter()

const { form } = useForm<ClassInfoApi.ClassQuery>({
  keyword: undefined,
  subject: undefined,
  classYear: undefined,
  term: undefined,
  grade: undefined,
  classCategory: undefined,
  campusId: undefined,
  classroomId: undefined,
  classTypeId: undefined,
  leadTeacherId: undefined,
  assistTeacherId: undefined,
  classStatus: undefined,
  saleStatus: undefined,
})
// 更多筛选
const filterCollapsed = ref<boolean>(true)

const {
  tableData,
  loading,
  pagination,
  search: searchData,
  handleDelete,
} = useTable(pagination => ClassInfoApi.getClassPage({ ...form, ...pagination }), { immediate: false })

const columns: TableInstanceColumns[] = [
  { title: '班级', dataIndex: 'name', slotName: 'name', fixed: 'left', width: 350 },
  { title: '年份科目', dataIndex: 'classYear', slotName: 'classYear', width: 150 },
  { title: '校区教室', dataIndex: 'classroomId', slotName: 'classroom', width: 108 },
  { title: '招生人数', dataIndex: 'enrollStudentCount', slotName: 'enrollStudentCount', align: 'right', width: 120 },
  { title: '班级限额', dataIndex: 'planStudentCount', align: 'right', width: 88 },
  // { title: '招生进度', dataIndex: 'enrollProgress', slotName: 'enrollProgress', width: 200 },
  { title: '上课进度', dataIndex: 'classProgress', slotName: 'classProgress', width: 240 },
  { title: '班级状态', dataIndex: 'classStatus', slotName: 'classStatus', minWidth: 120, filterable: {
    filters: useDictFilterOptions('ClassStatusEnum'),
    multiple: true,
  } },
  { title: '总价', dataIndex: 'totalPrice', slotName: 'totalPrice', minWidth: 120 },
  { title: '上架状态', dataIndex: 'saleStatus', slotName: 'saleStatus', minWidth: 120, filterable: {
    filters: useDictFilterOptions('SaleStatusEnum'),
    multiple: false,
  } },
  { title: '操作', slotName: 'action', width: 88, fixed: 'right' },
]

// 总览数据
const summary = ref<ClassInfoApi.ClassInfoSummaryResp>({
  classCount: 0,
  planStudentCount: 0,
  enrollStudentCount: 0,
  passedStudentCount: 0,
  totalLessonCount: 0,
  completedLessonCount: 0,
})
const search = async () => {
  searchData()
  summary.value = await ClassInfoApi.getClassSummary(form)
}

// 删除
const onDelete = (item: ClassInfoApi.ClassInfoResp) => {
  return handleDelete(() => ClassInfoApi.removeClass(item.id), {
    content: `是否确定删除该班级？`,
    showModal: true,
  })
}

// 创建
const onCreate = () => {
  router.push({ path: '/education/class/create' })
}

// 批量创建
const onCreateBatch = () => {
  router.push({ path: '/education/class/batch-create' })
}

const onEdit = (row, isRenewal: boolean = false) => {
  const query: { id: string, isRenewal?: string | number } = { id: row.id }
  if (isRenewal) {
    query.isRenewal = 1
  }
  router.push({ path: '/education/class/create', query })
}

const onClose = async (item: ClassInfoApi.ClassInfoResp) => {
  Modal.warning({ title: '提示', content: `是否确定关闭班级 [${item.name}]?`, hideCancel: false, okButtonProps: { status: 'danger' }, onOk: async () => {
    await ClassInfoApi.closeClass(item.id)
    Message.success('关班成功')
    search()
  } })
}

// 筛选
const onFilterChange = (dataIndex, filteredValues) => {
  form[dataIndex] = filteredValues
}

const changeStatus = async (record) => {
  await ClassInfoApi.updateSaleStatus({ classId: record.id, status: record.saleStatus })
  Message.success('修改成功')
  search()
}

const onShowPendingPayStudent = (classId: string) => {
  console.log('onShowPendingPayStudent: ', classId)
}

const debouncedSearch = useDebounceFn(() => search(), 100)

// watchEffect(() => console.log(route.query))
// watch(() => route.query, () => Object.assign(form, route.query), { immediate: true })
watch(() => form, () => debouncedSearch(), { deep: true, immediate: true })

const onExportExcel = () => {
  useDownload(() => ClassInfoApi.exportClassInfo(form))
}
</script>

<template>
  <ProPage title="班级列表" description="管理机构班级信息">
    <template #title-right>
      <div class="ml-100px flex">
        <StatisticsItem tip="班级数量" icon="count" unit="个" :count="summary.classCount" />
        <StatisticsItem tip="招生情况" icon="count" unit="人" :count="`${summary.enrollStudentCount}/${summary.planStudentCount}`" />
        <StatisticsItem tip="上课情况" icon="count" unit="节" :count="`${summary.completedLessonCount}/${summary.totalLessonCount}`" />
      </div>
    </template>
    <template #extra>
      <a-space>
        <a-button v-permission="['edu:class:write']" type="text" @click="onCreateBatch">
          批量创建
        </a-button>
        <a-button v-permission="['edu:class:write']" type="primary" @click="onCreate">
          <template #icon>
            <icon-plus />
          </template>
          创建班级
        </a-button>
      </a-space>
    </template>
    <ProTable
      :data="tableData"
      :columns="columns"
      :loading="loading"
      :pagination="pagination"
      @refresh="search"
      @filter-change="onFilterChange"
    >
      <template #search-panel>
        <a-space direction="vertical" size="medium">
          <a-space>
            <label class="label">关键词</label>
            <a-input-search
              v-model="form.keyword"
              class="!min-w-360px"
              placeholder="班级名称关键词"
              search-button
              allow-clear
              @press-enter="search"
            />
            <CollapseButton v-model="filterCollapsed" />
          </a-space>
          <a-space v-show="filterCollapsed" direction="vertical" size="medium">
            <a-space>
              <label class="label">学期年级</label>
              <YearTermCascader v-model:class-year="form.classYear" v-model:term="form.term" class="!min-w-200px" check-strictly />
              <DictSelect v-model="form.grade" type="select" code="Grade" placeholder="年级" class="!min-w-120px" multiple />
              <DictSelect v-model="form.subject" type="select" code="Subject" placeholder="科目" class="!w-120px" />
              <ClassTypeSelect v-model="form.classTypeId" placeholder="班型" class="!min-w-150px" />
            </a-space>

            <a-space>
              <label class="label">其他条件</label>
              <DictSelect v-model="form.classCategory" type="button" code="ClassCategoryEnum" placeholder="类型" />
              <EmployeeSelect v-model="form.leadTeacherId" type="LEAD_TEACHER" placeholder="主讲老师" class="!min-w-150px" />
              <ClassroomCascader v-model:campus-id="form.campusId" v-model:classroom-id="form.classroomId" class="!min-w-200px" check-strictly />
            </a-space>
          </a-space>
        </a-space>
      </template>
      <template #toolbar-right>
        <a-button v-permission="['edu:class:read']" type="text" size="medium" @click="onExportExcel">
          <template #icon>
            <icon-download />
          </template>
          <span>导出</span>
        </a-button>
      </template>

      <template #name="{ record }">
        <CellClassInfo :id="record.id" :name="record.name" :lead-teacher-name="record.leadTeacherName" :assist-teacher-name="record.assistTeacherName" />
      </template>
      <template #classYear="{ record }">
        <DictLabel v-model="record.grade" code="Grade" /> · <DictLabel v-model="record.subject" code="Subject" />
        <div class="text-13px text-gray-4">
          {{ record.classYear }}年 · <DictLabel v-model="record.term" code="TermEnum" />
        </div>
      </template>
      <template #classroom="{ record }">
        <div>{{ record.classroomName || '-' }}</div>
        <div class="text-13px text-gray-4">
          {{ record.campusName }}
        </div>
      </template>
      <template #enrollStudentCount="{ record }">
        <div class="flex-row-end-center">
          <a-trigger trigger="click" @show="onShowPendingPayStudent(record.id)">
            <a-tag v-if="record.pendingPayCount" size="small" color="red" class="cursor-pointer">
              {{ record.pendingPayCount }}人未付
            </a-tag>
            <template #content>
              <!-- <a-empty /> -->
            </template>
          </a-trigger>
          <span class="w-18px">{{ record.enrollStudentCount }}</span>
        </div>
      </template>
      <template #enrollProgress="{ record }">
        <div>
          <a-progress :percent="record.planStudentCount === 0 ? 0 : record.enrollStudentCount / record.planStudentCount " :show-text="true" :steps="record.planStudentCount" size="small">
            <template #text>
              {{ record.enrollStudentCount || 0 }}/{{ record.planStudentCount || 0 }}
            </template>
          </a-progress>
          <div class="mt-1 flex cursor-pointer flex-justify-between font-size-[13px]">
            <a-trigger trigger="click" @show="onShowPendingPayStudent(record.id)">
              <a-tag v-if="record.pendingPayCount" size="small" color="red">
                {{ record.pendingPayCount }}人未支付
              </a-tag>
              <template #content>
                <div class="demo-arrow">
                  <a-empty />
                </div>
              </template>
            </a-trigger>
          </div>
        </div>
      </template>
      <template #totalPrice="{ record }">
        <span class="text-#ff7d00">￥{{ record.totalPrice || 0 }}</span>
      </template>
      <template #classProgress="{ record }">
        <div>
          <a-progress :percent="!record.totalLessonCount ? 0 : record.completedLessonCount / record.totalLessonCount " :stroke-width="6">
            <template #text>
              {{ record.completedLessonCount || 0 }}/{{ record.totalLessonCount || 0 }}
            </template>
          </a-progress>
          <span class="mt-1 text-13px text-gray-4">{{ record.arrangeTemplate?.startDate }} ~ {{ record.arrangeTemplate?.endDate }}</span>
        </div>
      </template>
      <template #classStatus="{ record }">
        <ClassStatus code="ClassStatusEnum" :status="record.classStatus" />
      </template>
      <template #saleStatus="{ record }">
        <a-switch v-model="record.saleStatus" type="round" :checked-value="1" :unchecked-value="0" @change="changeStatus(record)" />
      </template>
      <template #action="{ record }">
        <a-space>
          <a-dropdown trigger="hover">
            <a-link v-permission="['education:student:write']">
              操作
              <icon-down />
            </a-link>
            <template #content>
              <a-doption @click="onEdit(record)">
                复制
              </a-doption>
              <a-doption @click="onEdit(record, true)">
                续班
              </a-doption>
              <a-doption @click="onClose(record)">
                关班
              </a-doption>
              <a-doption @click="onDelete(record)">
                删除
              </a-doption>
            </template>
          </a-dropdown>
        </a-space>
      </template>
    </ProTable>
  </ProPage>
</template>

<style lang="less" scoped>
.label {
  display: inline-block;
  width: 60px;
  text-align: right;
  flex-shrink: 0;
  margin-right: 10px;
  color: var(--color-text-1);
}
</style>
